package com.deram.ctin.common.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import java.io.*;
import java.nio.charset.Charset;

/**
 * @author zhangcm
 * @version 1.0, 2017/9/25
 */
public class ITextPdfUtils {

    private ITextPdfUtils(){}

    public static InputStream create(InputStream htmlInputStream, InputStream inCssFile, String resourcesRootPath){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, os);
            document.open();
            Charset charset = Charset.forName("UTF-8");
            FontProvider fontProvider = new XMLWorkerFontProvider();
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, htmlInputStream, inCssFile, charset, fontProvider, resourcesRootPath);
            document.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new ByteArrayInputStream(os.toByteArray());
    }
}
